package com.jy.modules.cims.platform.controller;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.controller.CimsBaseController;
import com.jy.modules.cims.common.exception.CimsExceptionConstant;
import com.jy.modules.cims.common.exception.SysAssistException;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmRefundPlanService;
import com.jy.modules.cims.component.sysAssist.ExportAndImport;
import com.jy.modules.cims.data.common.dto.TCMmRefundPlanDTO;
import com.jy.modules.cims.data.dto.CooperorgFormCreditTotalDto;
import com.jy.modules.cims.data.dto.RefundPlanDTO;
import com.jy.modules.cims.deal.service.LoanDealService;
import com.jy.modules.cims.subsidiary.service.SubsidiaryService;
import com.jy.platform.core.message.DataMsg;
import com.jy.platform.core.message.PageParameter;
import com.jy.platform.core.message.PageUtil;
import com.jy.platform.core.message.QueryReqBean;
import com.jy.platform.restservice.exception.AbaboonException;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;

/**
 * 还款计划表信息
 * <b>类名称：</b>PlatformPlanController <br/>
 * <b>类描述：</b><br/>
 * <b>修改人：</b><br/>
 * <b>修改备注：</b><br/>
 * <b>版本信息：</b>v1.0.0<br/>
 */
@Controller
@Scope("prototype")
@RequestMapping("/platformPlan")
public class PlatformPlanController extends CimsBaseController {
	
	@Autowired
	@Qualifier("com.jy.modules.cims.subsidiary.service.SubsidiaryService")
	public SubsidiaryService subsidiaryService;
	
	@Autowired
    @Qualifier("com.jy.modules.cims.component.common.service.TCMmRefundPlanService")
	
    private TCMmRefundPlanService refundPlanService;
	
	/**
     * 通过 Controller 请求 跳转 进入至相关 页面
     */
    @RequestMapping(value = "/prepareExecute/{operate}")
    public ModelAndView execute(@PathVariable("operate") String operate) throws AbaboonException {
        ModelAndView model = new ModelAndView();
        
        if("toQuery".equals(operate)){//跳转至 查询页面
        	model.setViewName("cims/platformPlan/queryTCMmPlatformPlan");	
        }
        
        return model;
    }
    /**
     * 分页查询  证大还款计划
     * @Title getRefundPlanListByDay
     * @Description TODO
     * @param request
     * @param dto
     * @param dataMsg
     * @return 
     * DataMsg 
     * @update 
     * @throws
     */
    @RequestMapping(value = "/getRefundPlanListByDay")
	@ResponseBody
    public DataMsg getRefundPlanListByDay(HttpServletRequest request, TCMmRefundPlanDTO dto, @ModelAttribute DataMsg dataMsg)throws Exception{
    	Map<String, Object> searchParams = new HashMap<String, Object>();
    	//字符串进行转换
    	String creditorCodes = dto.getCreditorCode();
    	creditorCodes="'"+creditorCodes.replaceAll(",","','")+"'";
		searchParams.put("dto", dto);
		searchParams.put("creditorCodes", creditorCodes);
		QueryReqBean params = new QueryReqBean();
		params.setSearchParams(searchParams);
		PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		
		if(SimpleStringUtils.hasText(dto.getCooperorgCode())){//如果有账单日才进行查询
	    	List<TCMmRefundPlanDTO> refundPlan  = refundPlanService.searchfundPlanListByPaging(params.getSearchParams());
			dataMsg.setData(refundPlan);
		}else{
			dataMsg.setData(null);
		}
		dataMsg.setTotalRows(pageInfo.getTotalCount());
    	return dataMsg;
    }
    
    
    /**
     *  导出  证大还款计划
     * @Title exportRefundPlan
     * @Description TODO
     * @param request
     * @param dto
     * @param dataMsg
     * @return 
     * DataMsg 
     * @update 
     * @throws
     */
    @RequestMapping(value = "/exportRefundPlan")
	@ResponseBody
    public void exportRefundPlan(HttpServletRequest request,HttpServletResponse response, TCMmRefundPlanDTO dto, @ModelAttribute DataMsg dataMsg) throws Exception{
    	Date date = new Date();
    	SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
    	formatter.format(date);
		String dealDate = formatter.format(date);
		String fileName = "还款计划"+dealDate;
		Map<String, Object> searchParams = new HashMap<String, Object>();
		//字符串进行转换
		String creditorCodes = dto.getCreditorCode()==null ? "" :dto.getCreditorCode(); 
    	creditorCodes="'"+creditorCodes.replaceAll(",","','")+"'";
    	searchParams.put("creditorCodes", creditorCodes);
    	searchParams.put("dto", dto);
        QueryReqBean params = new QueryReqBean();
        params.setSearchParams(searchParams);
    	PageParameter pageInfo = PageUtil.toPageParameter(dataMsg);
		params.setPageParameter(pageInfo);
		List<TCMmRefundPlanDTO> refundPlan = refundPlanService.searchfundPlanListByCreditandDate(params.getSearchParams());
		
		
    	ExportAndImport<TCMmRefundPlanDTO> exportAndImport = new ExportAndImport<TCMmRefundPlanDTO>();
    	String columnCode = CimsConstant.PLATFORMPLAN_RESULT_EXPORT_CODE;
    	String columnName = CimsConstant.PLATFORMPLAN_RESULT_EXPORT_NAME;
		HSSFWorkbook workbook;
		try {
			workbook = exportAndImport.exportExcelSubsidiary(fileName, columnCode, columnName, refundPlan);
			write(workbook, fileName, response);
		} catch (IOException e) {
			dataMsg.failed(e.getMessage());
			throw new SysAssistException(CimsExceptionConstant.LOADDETAIL_FORM_FAILED + ":证大还款计划导出结果" + e);
		}
    }
    
    /**
  	 * 页面输出
  	 * 
  	 * @param workbook
  	 * @param fileName
  	 * @param response
  	 * @throws IOException
  	 */
  	private void write(HSSFWorkbook workbook, String fileName, HttpServletResponse response) throws IOException {

  		try {
  			
  			response.setContentType("application/vnd.ms-excel");
  			response.setContentType("application/vnd.openxmlformatSs-officedocument.spreadsheetml.sheet");
  			response.setCharacterEncoding("UTF-8");
  			response.setHeader("content-disposition", "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO8859-1") + ".xls");
  			workbook.write(response.getOutputStream());
  			response.getOutputStream().flush();
  		} catch (Exception e) {
  			throw new SysAssistException(CimsExceptionConstant.EXPORT_EXCEL_FAIL + e.getMessage());
  		} finally {
  			response.getOutputStream().close();
  		}
  	}

}